package com.mt.checkerin;

import java.io.IOException;

import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mt.checkerin.model.PageForm;
import com.mt.checkerin.model.WebSite;

public class WebSiteVistor {

	private static Logger logger = LoggerFactory.getLogger(WebSiteVistor.class);
	
	private WebSite webSite;
	
	private HttpHelper http = new HttpHelper();
	
	private void init() {
	}
	
	public String visit( WebSite webSite) {
		try {
			
			
			do {
				
				PageForm form = webSite.getCurrentPageForm();
				processForm(form);
				
			} while(webSite.moveToNextForm());
			

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return null;
	}
	
	public void processForm(PageForm pageForm) throws ParseException, IOException {
		
		String url = pageForm.getUrl();

		logger.debug("Process form {0} : {1}", pageForm.getName(), url);
		
		String respBody;
		if (pageForm.getMethod().equals("POST")) {
			respBody = http.sendReuqest(url, 
					pageForm.getFormNamePairs(), 
					pageForm.getHeaderArray());
		} else {
			respBody = http.sendReuqest(url, 
					pageForm.getHeaderArray());
		}
		
		pageForm.setResponseBody(respBody);
		
	}
	
	

}
